import 'dart:io';

void main() {
  List<Map<String, double>> incomeList = [];
  List<Map<String, double>> expenseList = [];

  while (true) {
    print("\nWelcome to the Budget Management Application");
    print("Please choose an option:");
    print("1. Add income");
    print("2. Add expense");
    print("3. View summary");
    print("4. Exit");

    stdout.write("Enter your choice: ");
    String? choice = stdin.readLineSync();

    if (choice == '1') {
      addIncome(incomeList);
    } else if (choice == '2') {
      addExpense(expenseList);
    } else if (choice == '3') {
      viewSummary(incomeList, expenseList);
    } else if (choice == '4') {
      print("Exiting the application. Goodbye!");
      break;
    } else {
      print("Invalid choice! Please enter a number from 1 to 4.");
    }
  }
}

void addIncome(List<Map<String, double>> incomeList) {
  stdout.write("Enter income description: ");
  String description = stdin.readLineSync() ?? '';

  stdout.write("Enter income amount: ");
  double? amount = double.tryParse(stdin.readLineSync() ?? '');

  if (amount == null || amount <= 0) {
    print("Invalid amount! Please enter a positive number.");
  } else {
    incomeList.add({description: amount});
    print("Income added successfully.");
  }
}

void addExpense(List<Map<String, double>> expenseList) {
  stdout.write("Enter expense description: ");
  String description = stdin.readLineSync() ?? '';

  stdout.write("Enter expense amount: ");
  double? amount = double.tryParse(stdin.readLineSync() ?? '');

  if (amount == null || amount <= 0) {
    print("Invalid amount! Please enter a positive number.");
  } else {
    expenseList.add({description: amount});
    print("Expense added successfully.");
  }
}

void viewSummary(List<Map<String, double>> incomeList, List<Map<String, double>> expenseList) {
  double totalIncome = incomeList.fold(0, (sum, item) => sum + item.values.first);
  double totalExpenses = expenseList.fold(0, (sum, item) => sum + item.values.first);
  double netProfit = totalIncome - totalExpenses;

  print("\n--- Budget Summary ---");
  print("Total Income: \$${totalIncome.toStringAsFixed(2)}");
  print("Total Expenses: \$${totalExpenses.toStringAsFixed(2)}");

  if (netProfit >= 0) {
    print("Your net profit is \$${netProfit.toStringAsFixed(2)}");
    double tax = netProfit * 0.15;
    print("Tax to be paid (15%): \$${tax.toStringAsFixed(2)}");
  } else {
    print("Your net loss is \$${netProfit.abs().toStringAsFixed(2)}");
  }
}
